<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/28
 * Time: 17:01
 */
namespace App\HttpController\V1;
use app\Common\Checking;
use App\Utility\Pool\ThumImage;
use EasySwoole\Http\AbstractInterface\Controller;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

class Code extends BaseWithDb
{
    protected $url='http://47.52.46.86:777/';
    protected $web_url='';
    protected $bg='Upload/qrcode.jpg';
    public function index()
    {
//        $conf = $this->db->where( 'name', 'stock_right_little' )->getOne( 'config', 'tip,value' );
//        $demo=new Login();
//        $this->db->startTransaction();
//        try{
//            $info=$demo->demo($this->db);
//            $this->db->commit();
//        }catch (\Exception $exception){
//            $this->db->rollback();
//        }
//        return $this->writeJson( 200, $info, 'ok' );
    }
    /**
     * 推广二维码
     * @return \think\response\Json
     */
    public function code($model,$user_id){
        $user_info=$model->where('id',$user_id)->getOne('users');
        $uid=$user_id;
        $register_url=$this->web_url.'/register?uid='.$user_info['uuid'];
//        if ($user_info['qrcode_url']!='' && $user_info['qrcode_urls']!='' ){
//            $data['img']=$this->url.$user_info['qrcode_url'];#
//            $data['url']=$register_url;
            return $this->writeJson( 200, $user_id, '获取成功');
//        }
        $qrCode = new QrCode($register_url);
        $qrCode->setSize(300);
        $qrCode->setWriterByName('png');
        $qrCode->setMargin(5);
        $qrCode->setEncoding('UTF-8');
        $qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
//        $qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER);
//        $qrCode->setLogoPath(__DIR__.'/../assets/images/symfony.png');
        $qrCode->setLogoSize(150, 200);
        $qrCode->setRoundBlockSize(true);
        $qrCode->setValidateResult(false);
        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
//        header('Content-Type: '.$qrCode->getContentType());
//        $qrCode->writeFile(EASYSWOOLE_ROOT.'/Upload/usersimg/qrcode/short/qrcode'.$uid.'.png');
        $qrCode->writeFile(EASYSWOOLE_ROOT.'/Upload/usersimg/qrcode'.$uid.'.png');
//        $long=$this->h_code($uid,'',$user_info['uuid'],$user_info['uuid']);
//        $short=$this->long_code($uid,'',$user_info['uuid'],$user_info['uuid']);
//        return $this->writeJson(200,$long);
        $img='/Upload/usersimg/qrcode'.$uid.'.png';#
        $data['url']=$register_url;
        $data['img']=$this->url.$img;
        #二维码存入数据库
        $model->where('id',$user_id)->update('users',['qc_code'=>$img]);
//        return $this->writeJson( 200, $data, '获取成功');
        return $data;
    }
    /**
     * @param $uid 用戶id
     * @param $head_path 頭像路徑
     * @param string $teststr 用戶昵称
     * $teststr1 uuid
     * @return string
     */
    public function h_code($uid,$head_path,$teststr,$teststr1){
        $code='Upload/usersimg/qrcode/qrcode'.$uid.'.png';//二维码
        $last='Upload/usersimg/qrcode/qrcode'.$uid.'.png';//生成的二维码
        $path_1=  $this->url.$this->bg;//背景图
        $width=getimagesize($path_1);
        $path_2 = $this->url.$code;   //二维码图片

        $image_1 = imagecreatefromjpeg($path_1);
        $image_2 = imagecreatefrompng($path_2);
        // 创建真彩画布
        $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));

        // 为真彩画布创建白色背景
        $color = imagecolorallocate($image_3, 255, 255, 255);
        imagefill($image_3, 0, 0, $color);
        // 设置透明
        $font=EASYSWOOLE_ROOT.'/Upload/fonts/fzltxh.ttf';
        // 复制图片一到真彩画布中（重新取样-获取透明图片）
        $im = imagecreatetruecolor(10, 10);
        $black = imagecolorallocate($im, 255,69, 0);
        mb_internal_encoding("UTF-8"); // 设置编码
        $fontBox = imagettfbbox(20, 0, $font, $teststr);
//        $fontBox1 = imagettfbbox(20, 0, $font, $teststr1);
        imagettftext($image_1, 38, 0, ($width[0]-$fontBox[2])/2-40, 650, $black,$font , $teststr);//将文字写到图片中
        imagettftext($image_1, 38, 0, ($width[0]-$fontBox[2])/2-39, 650, $black,$font , $teststr);//将文字写到图片中
        imagettftext($image_1, 38, 0, ($width[0]-$fontBox[2])/2-38, 650, $black,$font , $teststr);//将文字写到图片中
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
        // 与图片二合成
        imagecopymerge($image_3, $image_2, 220, 700, 0, 0, imagesx($image_2), imagesy($image_2), 100);
        // 输出合成图片
        imagepng($image_3,EASYSWOOLE_ROOT.'/'.$last);

        #获取图片的宽高
//        $url = $head_path;
//        if( @fopen( $url, 'r' ) )    {
//            $head_paths=$head_path;
//        }else{
//            $head_paths=$this->default_head;
//        }
//        $head = $this->yuanjiao($head_paths);#处理图像圆角
//         为真彩画布创建白色背景
//        $color = imagecolorallocate($head, 223,253,253);
//        imagefill($head, 0, 0, $color);
//         设置透明
//        imagesavealpha($head, true);
//         与图片二合成
//        imagecopymerge($image_3, $head, ($width[0]-80)/2, 30, 0, 0, imagesx($head), imagesy($head), 100);
//         输出合成图片
//        imagepng($image_3,'userimg/qrcode'.$uid.'.png');
        $source =  $last;//原图片名称
        $dst_img = $last;//压缩后图片的名称
        $percent = 0.5;  #原图压缩，不缩放，但体积大大降低
//        $image = (new ThumImage($source,$percent))->compressImg($dst_img);
//        return $this->writeJson(200,12);

        return $last;
    }
    #头像圆化
    function yuanjiao($url){
        $sw = getimagesize($url)[0];
        $sh=getimagesize($url)[1]; // original size
        $w=98; $h=100;
        $original_path= $url;
        $src = imagecreatefromstring(file_get_contents($original_path));
        $newpic = imagecreatetruecolor($w,$h);
        imagecopyresampled($src, $src, 0,0, 0,0, $w, $h, $sw, $sh);//缩放图片
        imagealphablending($newpic,false);
        $transparent = imagecolorallocatealpha($newpic, 255, 255, 255, 127);
        $r=$w/2;
        for($x=0;$x<$w;$x++) {
            for ($y = 0; $y < $h; $y++) {
                $c = imagecolorat($src, $x, $y);
                $_x = $x - $w / 2;
                $_y = $y - $h / 2;
                if ((($_x * $_x) + ($_y * $_y)) < ($r * $r)) {
                    imagesetpixel($newpic, $x, $y, $c);
                } else {
                    imagesetpixel($newpic, $x, $y, $transparent);
                }
            }
        }
        return $newpic;
    }
    /**
     *  blog:http://www.zhaokeli.com
     * 处理成圆图片,如果图片不是正方形就取最小边的圆半径,从左边开始剪切成圆形
     * @param  string $imgpath [description]
     * @return [type]          [description]
     */
    function yuan_img($imgpath = './tx.jpg') {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
//        $wh  = getimagesize($imgpath);
//        $w   = $wh[0];
//        $h   = $wh[1];
        $w=98; $h=100;
        $w   = min($w, $h);
        $h   = $h;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $w / 2; //圆半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }


}